﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
//using MySql.Data.MySqlClient;
using System.Data;
using Telerik.Web.UI;
using System.Globalization;
using KPIS.GERP.SECURITY.BLL;
using KPIS.GERP.GHRMS.APP.Classes;
using KPIS.GERP.GHRMS.BLL;
using KPIS.GERP.GHRMS.DAL;
using KPIS.GERP.GHRMS.MODEL;
using System.Text;
using KPIS.DBM;
using System.Data.SqlClient;

namespace KPIS.GERP.GHRMS.APP.App_UI.Forms
{
    public partial class HRDEvaluationSupervisor : System.Web.UI.Page
    {
        private UserBLL userBLL = new UserBLL();
        private SsMng ssMng = new SsMng();
        private HRDEvaluationBLL cmd = new HRDEvaluationBLL();
        private AbsenceDAL ab = new AbsenceDAL();
        private AbsenceRuleDAL abr = new AbsenceRuleDAL();
        private Main main = new Main();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                string strUserSeq = Request.QueryString["YSeq"].ToString();
                GetUserInfo(strUserSeq);
                PageViewPerformanceAgreement();
                Round();

                rpt.DataSource = cmd.GetData();
                rpt.DataBind(); 

            }
        }

        public void AbsenceDetail(DateTime StartDate, DateTime EndDate, string strEmpSeq)
        {
            IList<hrm_ps_absence> HrmAbsence;
            IList<rule_absence> HrmAbsenceRule;
            string emp_seq = Request.QueryString["ESeq"].ToString();
            int intQuotaSick, intQuotaLeave, intQuotaHoliday, intQuotaLate, intQuotaOther = 0;
            double dblSick, dblLeave, dblHoliday, dblLate, dblOther = 0.0;
             
                HrmAbsence = ab.GetAbsenceDays(strEmpSeq);
                var Absence = (from l in HrmAbsence
                               where l.absence_type_seq == 1
                               where (l.start_date >= StartDate) && (l.start_date <= EndDate)
                               select l.day_count).Sum(l => l.Value);
                dblSick = Convert.ToDouble(Absence);
                lblSick.Text = dblSick.ToString();

                Absence = (from l in HrmAbsence
                           where l.absence_type_seq == 3
                           where (l.start_date >= StartDate) && (l.start_date <= EndDate)
                           select l.day_count).Sum(l => l.Value);
                dblLeave = Convert.ToDouble(Absence);
                lblLeave.Text = dblLeave.ToString();

                Absence = (from l in HrmAbsence
                           where l.absence_type_seq == 4
                           where (l.start_date >= StartDate) && (l.start_date <= EndDate)
                           select l.day_count).Sum(l => l.Value);
                dblHoliday = Convert.ToDouble(Absence);
                lblHoliday.Text = dblHoliday.ToString();

                Absence = (from l in HrmAbsence
                           where l.absence_type_seq == 10
                           where (l.start_date >= StartDate) && (l.start_date <= EndDate)
                           select l.day_count).Sum(l => l.Value);
                dblLate = Convert.ToDouble(Absence);
                lblLate.Text = dblLate.ToString();

                Absence = (from l in HrmAbsence
                           where l.absence_type_seq != 1 && l.absence_type_seq != 3 && l.absence_type_seq != 4 && l.absence_type_seq != 10
                           where (l.start_date >= StartDate) && (l.start_date <= EndDate)
                           select l.day_count).Sum(l => l.Value);
                dblOther = Convert.ToDouble(Absence);
                lblOther.Text = dblOther.ToString();

                // Quota //
                HrmAbsenceRule = abr.GetAbsenceRulesByEmpSeq(strEmpSeq).ToList();
                var Quota = (from l in HrmAbsenceRule
                             where l.absence_type_seq == 1  // ลาป่วย
                             select l.day_limit).FirstOrDefault();
                intQuotaSick = Convert.ToInt32(Quota);
                lblLimitSick.Text = intQuotaSick.ToString("#");

                Quota = (from l in HrmAbsenceRule
                         where l.absence_type_seq == 3  // ลากิจ
                         select l.day_limit).FirstOrDefault();
                intQuotaLeave = Convert.ToInt32(Quota);
                lblLimitLeave.Text = intQuotaLeave.ToString("#");

                Quota = (from l in HrmAbsenceRule
                         where l.absence_type_seq == 4  // ลาพักผ่อน
                         select l.day_limit).FirstOrDefault();
                intQuotaHoliday = Convert.ToInt32(Quota);
                lblLimitHoliday.Text = intQuotaHoliday.ToString("#");

                Quota = (from l in HrmAbsenceRule
                         where l.absence_type_seq == 10 // มาสาย
                         select l.day_limit).FirstOrDefault();
                intQuotaLate = Convert.ToInt32(Quota);
                lblLimitLate.Text = intQuotaLate.ToString("#");

                Quota = (from l in HrmAbsenceRule
                         where l.absence_type_seq != 1 && l.absence_type_seq != 3 && l.absence_type_seq != 4 && l.absence_type_seq != 10
                         select l.day_limit).Sum();

                intQuotaOther = Convert.ToInt32(Quota);
                lblLimitOther.Text = intQuotaOther.ToString("#");

                int intSumQuota = intQuotaSick + intQuotaLeave + intQuotaHoliday + intQuotaLate + intQuotaOther;
                lblLimitSum.Text = intSumQuota.ToString();

                double dblSumAbsence = dblSick + dblLeave + dblHoliday + dblLate + dblOther;
                lblSum.Text = dblSumAbsence.ToString(); 
        }
        
        public void Round()
        {
            int intEvalRoundSeq = Convert.ToInt32(Request.QueryString["RSeq"]);
            int intEmpSeq = Convert.ToInt32(Request.QueryString["ESeq"]);

            if (intEvalRoundSeq != 0)
            {
                DataTable dtRound = cmd.Round(intEvalRoundSeq);
                int intYear = Convert.ToInt32(dtRound.Rows[0]["round_year"]);
                lblRound.Text = dtRound.Rows[0]["round_and_year"].ToString();

                DateTime dateStartDate = Convert.ToDateTime(dtRound.Rows[0]["round_start_date"]);
                DateTime dateEndDate = Convert.ToDateTime(dtRound.Rows[0]["round_end_date"]);

                string strstartDate = dateStartDate.ToString("dd/MM/yyyy", new CultureInfo("th-TH"));
                string strendDate = dateEndDate.ToString("dd/MM/yyyy", new CultureInfo("th-TH"));

                pnlAbsent.GroupingText = "ข้อมูลการลา สรุปวันลาตั้งแต่วันที่ " + strstartDate + "   ถึงวันที่ " + strendDate;

                AbsenceDetail(dateStartDate, dateEndDate, intEmpSeq.ToString());
                
                DataTable dtCheckOther = cmd.CheckOtherScore(intEmpSeq, intEvalRoundSeq);

                if (dtCheckOther.Rows.Count > 0)
                {                    
                    DataRow[] drKPA = dtCheckOther.Select(string.Format("table_ref = '{0}'", "hrm_perf_key_performance_area"), "");
                    DataRow[] drStrategy = dtCheckOther.Select(string.Format("table_ref = '{0}'", "hrm_perf_job_assignment"), "");
                    DataRow[] drCoreCompetency = dtCheckOther.Select(string.Format("table_ref = '{0}'", "hrm_perf_position_core_competency"), "");
                    DataRow[] drIDP = dtCheckOther.Select(string.Format("table_ref = '{0}'", "hrm_perf_individual_dev_plan"), "");
                  

                    DisibleRadioButtonListKPA(drKPA);
                    DisibleRadioButtonListStrategy(drStrategy);
                    DisibleRadioButtonListCoreCompetency(drCoreCompetency);
                    DisibleRadioButtonListIDP(drIDP);

                    DataTable dtLoadResultIDP = cmd.LoadResultIDP(intEmpSeq, intEvalRoundSeq);
                    LoadResultIdp(dtLoadResultIDP);                    

                }
                
            }

        }

        public void GetUserInfo(string UserSequence)
        {
            DataSet ds = userBLL.LoadUser(Int32.Parse(UserSequence), (int?)null, (int?)null, "");


            if (ds != null)
            {

                DataTable dt = null;

                dt = ds.Tables[0];
                if (dt.Rows.Count > 0)
                    lblName.Text = dt.Rows[0]["USER_NAME"].ToString();
                lblPosition.Text = dt.Rows[0]["POS_NAME"].ToString();
                lblLevel.Text = dt.Rows[0]["CLASS_NAME"].ToString();
                lblJobSite.Text = dt.Rows[0]["JOB_SITE_NAME"].ToString();

                if (dt.Rows[0]["DATE_ADMITTED"].ToString() == "")
                {
                    lblDateAdmit.Text = "";
                }
                else
                {
                    lblDateAdmit.Text = Convert.ToDateTime(dt.Rows[0]["DATE_ADMITTED"].ToString()).ToString("d MMMM yyyy", new CultureInfo("th-TH"));

                }

                if (dt.Rows[0]["DATE_WORK_START"].ToString() == "")
                {
                    lblDateWorkStart.Text = "";
                }
                else
                {
                    lblDateWorkStart.Text = Convert.ToDateTime(dt.Rows[0]["DATE_WORK_START"].ToString()).ToString("d MMMM yyyy", new CultureInfo("th-TH"));

                }
            }
        }

        public void PageViewPerformanceAgreement()
        {
            int intEmpSeq = Convert.ToInt32(Request.QueryString["ESeq"]);

            DataTable dt = cmd.LoadGoalObjective(intEmpSeq);
            grdRadDevelopmentNeed.DataSource = String.Empty;

            if (dt.Rows.Count > 0)
            {
                txtGoalObjective.Text = dt.Rows[0]["goal_objective"].ToString();
                txtRadActionPlan.Text = dt.Rows[0]["action_plan"].ToString();

                grdRadDevelopmentNeed.DataSource = cmd.LoadGridDevelopmentNeed(intEmpSeq);
                grdRadDevelopmentNeed.DataBind();
            }
        }

        public void LoadGridKeyPerformanceArea(int intPosSeq)
        {
            grdRadKPA.DataSource = cmd.LoadGridKPA(intPosSeq);
            grdRadKPA.DataBind();
        }

        public void LoadGridCoreCompetency(int intPosSeq)
        {
            grdRadCoreCompetency.DataSource = cmd.LoadGridCoreCompetency(intPosSeq);
            grdRadCoreCompetency.DataBind();
        }

        public void LoadGridIDP(int intPosSeq)
        {
            grdRadIDP.DataSource = cmd.LoadGridIDP(intPosSeq);
            grdRadIDP.DataBind();
        }

        public void LoadGridStrategyProject(int intRoundYear, DateTime dateStartDate, DateTime dateEndDate)
        {
            grdRadStrategyProject.DataSource = cmd.LoadGridStrategyProject(intRoundYear, dateStartDate, dateEndDate, Convert.ToInt32(Request.QueryString["ESeq"]));
            grdRadStrategyProject.DataBind();
        }

        protected void grdRadKPA_ItemDataBound(object sender, GridItemEventArgs e)
        {
            DataTable dtPosSeq = cmd.getPosSeq(Convert.ToInt32(Request.QueryString["ESeq"]));
            int intPosSeq = Convert.ToInt32(dtPosSeq.Rows[0]["pos_seq"]);


            if (e.Item is GridDataItem)
            {
                int intEvaluationListSeq = Convert.ToInt32(cmd.LoadGridKPA(intPosSeq).Rows[0]["evaluation_list_seq"]);

                GridDataItem item = e.Item as GridDataItem;

                RadioButtonList rblEmployeeScore = item.FindControl("rblEmployeeScore") as RadioButtonList;
                RadioButtonList rblSupervisorScore = item.FindControl("rblSupervisorScore") as RadioButtonList;

                rblEmployeeScore.DataSource = cmd.LoadScoreFormat(intEvaluationListSeq);
                rblEmployeeScore.DataBind();

                rblSupervisorScore.DataSource = cmd.LoadScoreFormat(intEvaluationListSeq);
                rblSupervisorScore.DataBind();
            }

        }

        protected void grdRadStrategyProject_ItemDataBound(object sender, GridItemEventArgs e)
        {
            int intEvalRoundSeq = Convert.ToInt32(Request.QueryString["RSeq"]);
            DataTable dtRound = cmd.Round(intEvalRoundSeq);
            int intYear = Convert.ToInt32(dtRound.Rows[0]["round_year"]);
            DateTime dateStartDate = Convert.ToDateTime(dtRound.Rows[0]["round_start_date"]);
            DateTime dateEndDate = Convert.ToDateTime(dtRound.Rows[0]["round_end_date"]);

            if (e.Item is GridDataItem)
            {
                DataTable dt = cmd.LoadGridStrategyProject(intYear, dateStartDate, dateEndDate, Convert.ToInt32(Request.QueryString["ESeq"]));

                if(dt.Rows.Count > 0)
                {
                    int intEvaluationListSeq = Convert.ToInt32(dt.Rows[0]["evaluation_list_seq"]);

                    GridDataItem item = e.Item as GridDataItem;
                    RadioButtonList rblEmployeeScore = item.FindControl("rblEmployeeScore") as RadioButtonList;
                    RadioButtonList rblSupervisorScore = item.FindControl("rblSupervisorScore") as RadioButtonList;

                    rblEmployeeScore.DataSource = cmd.LoadScoreFormat(intEvaluationListSeq);
                    rblEmployeeScore.DataBind();

                    rblSupervisorScore.DataSource = cmd.LoadScoreFormat(intEvaluationListSeq);
                    rblSupervisorScore.DataBind();
                }
                
            }
        }

        protected void grdRadCoreCompetency_ItemDataBound(object sender, GridItemEventArgs e)
        {
            DataTable dtPosSeq = cmd.getPosSeq(Convert.ToInt32(Request.QueryString["ESeq"]));
            int intPosSeq = Convert.ToInt32(dtPosSeq.Rows[0]["pos_seq"]);

            if (e.Item is GridDataItem)
            {
                int intEvaluationListSeq = Convert.ToInt32(cmd.LoadGridCoreCompetency(intPosSeq).Rows[0]["evaluation_list_seq"]);

                GridDataItem item = e.Item as GridDataItem;
                RadioButtonList rblEmployeeScore = item.FindControl("rblEmployeeScore") as RadioButtonList;
                RadioButtonList rblSupervisorScore = item.FindControl("rblSupervisorScore") as RadioButtonList;

                rblEmployeeScore.DataSource = cmd.LoadScoreFormat(intEvaluationListSeq);
                rblEmployeeScore.DataBind();

                rblSupervisorScore.DataSource = cmd.LoadScoreFormat(intEvaluationListSeq);
                rblSupervisorScore.DataBind();
            }
        }

        protected void grdRadIDP_ItemDataBound(object sender, GridItemEventArgs e)
        {
            DataTable dtPosSeq = cmd.getPosSeq(Convert.ToInt32(Request.QueryString["ESeq"]));
            int intPosSeq = Convert.ToInt32(dtPosSeq.Rows[0]["pos_seq"]);

            if (e.Item is GridDataItem)
            {
                int intEvaluationListSeq = Convert.ToInt32(cmd.LoadGridIDP(intPosSeq).Rows[0]["evaluation_list_seq"]);

                GridDataItem item = e.Item as GridDataItem;
                RadioButtonList rblEmployeeScore = item.FindControl("rblEmployeeScore") as RadioButtonList;
                RadioButtonList rblSupervisorScore = item.FindControl("rblSupervisorScore") as RadioButtonList;

                rblEmployeeScore.DataSource = cmd.LoadScoreFormat(intEvaluationListSeq);
                rblEmployeeScore.DataBind();

                rblSupervisorScore.DataSource = cmd.LoadScoreFormat(intEvaluationListSeq);
                rblSupervisorScore.DataBind();
            }
        }

        protected void grdRadResultIDP_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                GridDataItem item = e.Item as GridDataItem;

                RadComboBox cboDevMethod = (RadComboBox)item.FindControl("cboRadDevMethod");

                cboDevMethod.DataSource = cmd.LoadDevelopmentMethod();
                cboDevMethod.DataBind();
                cboDevMethod.Items.Insert(0, new RadComboBoxItem("--- เลือกวิธีการพัฒนา ---", ""));
            }

        }

        protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            int intEvalRoundSeq = Convert.ToInt32(Request.QueryString["RSeq"]);
            int intEmpSeq = Convert.ToInt32(Request.QueryString["ESeq"]);

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                RadGrid rg = (RadGrid)e.Item.FindControl("grdRadResult");
                if (rg != null)
                {
                    DataRowView drv = (DataRowView)e.Item.DataItem;
                    rg.DataSource = cmd.GetSubData(Convert.ToInt32(drv["weight_header_seq"]), intEmpSeq, intEvalRoundSeq);
                    rg.DataBind();
                }
            }
        }

        protected void btnSave_Clicked(object sender, EventArgs e)
        {
            int intEmpSeq = Convert.ToInt32(Request.QueryString["ESeq"]);
            int intRoundSeq = Convert.ToInt32(Request.QueryString["RSeq"]);

            try
            {
                DataTable dtHeader = cmd.GetHeaderSchema(intEmpSeq, intRoundSeq);
                DataTable dtOther = cmd.GetSchemaOtherScore(intEmpSeq, intRoundSeq);

                dtHeader.TableName = "Header";
                dtOther.TableName = "Other";

                DataSet dsKPA = ScoreKPA(dtHeader, dtOther.Copy());
                DataSet dsStrategy = ScoreStrategyProject(dtHeader, dtOther.Copy());
                DataSet dsCC = ScoreCoreCompetency(dtHeader, dtOther.Copy());
                DataSet dsIDP = ScoreIDP(dtHeader, dtOther.Copy());

                string str = cmd.SaveEvaluationOtherScore(dsKPA, dsStrategy, dsCC, dsIDP, intEmpSeq, intRoundSeq);

                var strParamUser = Request.QueryString["YSeq"];
                var strParamRound = Request.QueryString["RSeq"];
                var strParamEmp = Request.QueryString["ESeq"];

                //Response.Redirect(string.Format("HRDEvaluationSupervisor.aspx?YSeq={0}&RSeq={1}&ESeq={2}&Re={3}", strParamUser, strParamRound, strParamEmp, 1));
                if (str == "Successfully")
                {
                    rpt.DataSource = cmd.GetData();
                    rpt.DataBind();

                    DataTable dt = cmd.LoadResultIDP(intEmpSeq, intRoundSeq);
                    grdRadResultIDP.DataSource = dt;
                    grdRadResultIDP.DataBind();

                    RadTabStrip1.FindTabByText("ผลการประเมิน").Selected = true;
                    RadMultiPage1.FindPageViewByID("pgvRadResult").Selected = true;
                }
            }
            catch (Exception ex)
            {
                Session["error"] = Convert.ToString(Session["error"]) + ex.Message;
            }
            finally
            {
                
            }
          
        }
                
        protected void btnSaveResult_Clicked(object sender, EventArgs e)
        {
            InsertAndEditResultIdpDevPlan();
        }

        protected DataSet ScoreKPA(DataTable dtHeader, DataTable dtOther)
        {
            Double dblTotalMaxValue = 0.0;
            Double dblSupGrandTotalIsWeight = 0.0;
            Double dblSupGrandTotalWeight = 0.0;
            Double dblSupTotalScore = 0.0;
            Double dblSupTotal = 0.0;
            bool isWeight = false;
            
            foreach (GridDataItem item in grdRadKPA.MasterTableView.Items)
            {
                int intScore = 0;
                int intFullScore = main.ConvertDefaultInt(item["full_score"].Text);
                int intWeight = main.ConvertDefaultInt(item["weight"].Text);
                int intId = main.ConvertDefaultInt(item.GetDataKeyValue("evaluation_detail_seq"));
                int intEvaluationListSeq = main.ConvertDefaultInt(item["evaluation_list_seq"].Text);

                isWeight = Convert.ToBoolean(main.ConvertDefaultInt(item["isdetailweight"].Text));
                
                DataRow[] dr = dtOther.Select(string.Format("evaluation_detail_seq = {0}", intId), "");
                DataRow[] drHeader = dtHeader.Select(string.Format("evaluation_list_seq = {0}", intEvaluationListSeq), "");
                
                RadioButtonList rblSupScore = (RadioButtonList)item.FindControl("rblSupervisorScore");

                if (rblSupScore != null)
                {
                    intScore = Convert.ToInt32(rblSupScore.SelectedValue);
                }

                RadTextBox txtSupComment = (RadTextBox)item.FindControl("txtSupervisorComment");
                string strComment = "";
                if (txtSupComment != null)
                {
                    strComment = txtSupComment.Text;
                }

                if (isWeight)
                {
                    dblSupTotal = (intScore * intWeight) / intFullScore;
                    dblSupTotalScore += intFullScore;
                }
                else
                {
                    dblTotalMaxValue += intFullScore;

                }
                dblSupGrandTotalIsWeight += dblSupTotal;
                dblSupGrandTotalWeight = (dblSupTotalScore / dblTotalMaxValue) * 100.0;

                //////////////////////////////////////////////////////////////////////////////
                if (drHeader.Length > 0)
                {
                    foreach (var rowHD in drHeader)
                    {
                        rowHD["remark"] = txtRadRemarkKPA.Text;

                        if (isWeight)
                        { rowHD["supervisor_total_score"] = dblSupGrandTotalIsWeight; }
                        else
                        { rowHD["supervisor_total_score"] = dblSupGrandTotalWeight; }

                        rowHD["updated_by"] = ssMng.EmpSeq;
                        rowHD["updated_when"] = DateTime.Now;
                    }
                }

                if (dr.Length > 0)
                {
                    foreach (var row in dr)
                    {
                        row["other_score"] = intScore;
                        row["other_comment"] = strComment;
                        row["updated_by"] = ssMng.EmpSeq;
                        row["updated_when"] = DateTime.Now;
                    }
                }
                else
                {
                    DataRow drow = dtOther.NewRow();
                    drow["evaluation_detail_seq"] = intId;
                    drow["other_seq"] = ssMng.EmpSeq;
                    drow["other_score"] = intScore;
                    drow["other_comment"] = strComment;
                    drow["created_by"] = ssMng.EmpSeq;
                    drow["created_when"] = DateTime.Now;
                    drow["record_status"] = "U";
                    dtOther.Rows.Add(drow);
                }
            }

            GridFooterItem footerItem = (GridFooterItem)grdRadKPA.MasterTableView.GetItems(GridItemType.Footer)[0];
            Label lblSupGrandTotal = (Label)footerItem.FindControl("lblFooterKPASupTotalScore");

            if (isWeight)
            {
                lblSupGrandTotal.Text = String.Format("{0:N0}", dblSupGrandTotalIsWeight) + " %";
            }
            else
            {
                lblSupGrandTotal.Text = String.Format("{0:N0}", dblSupGrandTotalWeight) + " %";
            }

            DataSet ds = new DataSet();
            ds.Tables.Add(dtHeader.Copy());
            ds.Tables.Add(dtOther.Copy());

            return ds;
        }

        protected DataSet ScoreStrategyProject(DataTable dtHeader, DataTable dtOther)
        {
            Double dblTotalMaxValue = 0.0;
            Double dblSupGrandTotalIsWeight = 0.0;
            Double dblSupGrandTotalWeight = 0.0;
            Double dblSupTotalScore = 0.0;
            Double dblSupTotal = 0.0;
            int intWeight = 0;
            bool isWeight = false;

            foreach (GridDataItem item in grdRadStrategyProject.MasterTableView.Items)
            {
                int intScore = 0;
                int intFullScore = main.ConvertDefaultInt(item["full_score"].Text);

                if (item["weight"].Text != "&nbsp;")
                {
                    intWeight = main.ConvertDefaultInt(item["weight"].Text);
                }

                
                int intId = Convert.ToInt32(item.GetDataKeyValue("evaluation_detail_seq"));
                int intEvaluationListSeq = main.ConvertDefaultInt(item["evaluation_list_seq"].Text);

                isWeight = Convert.ToBoolean(main.ConvertDefaultInt(item["isdetailweight"].Text));

                DataRow[] dr = dtOther.Select(string.Format("evaluation_detail_seq = {0}", intId), "");
                DataRow[] drHeader = dtHeader.Select(string.Format("evaluation_list_seq = {0}", intEvaluationListSeq), "");

                RadioButtonList rblSupScore = (RadioButtonList)item.FindControl("rblSupervisorScore");
                RadTextBox txtSupComment = (RadTextBox)item.FindControl("txtSupervisorComment");

                if (rblSupScore != null)
                {
                    intScore = Convert.ToInt32(rblSupScore.SelectedValue);
                }

                string strComment = "";
                if (txtSupComment != null)
                {
                    strComment = txtSupComment.Text;
                }

                if (isWeight)
                {
                    dblSupTotal = (intScore * intWeight) / intFullScore;
                    dblSupTotalScore += intFullScore;
                }
                else
                {
                    dblSupTotalScore += intScore;
                    dblTotalMaxValue += intFullScore;

                }
                dblSupGrandTotalIsWeight += dblSupTotal;
                dblSupGrandTotalWeight = (dblSupTotalScore / dblTotalMaxValue) * 100.0;

                ///////////////////////////////////////////////////////////////////////
                if (drHeader.Length > 0)
                {
                    foreach (var rowHD in drHeader)
                    {
                        rowHD["remark"] = txtRadRemarkStrategy.Text;

                        if (isWeight)
                        { rowHD["supervisor_total_score"] = dblSupGrandTotalIsWeight; }
                        else
                        { rowHD["supervisor_total_score"] = dblSupGrandTotalWeight; }

                        rowHD["updated_by"] = ssMng.EmpSeq;
                        rowHD["updated_when"] = DateTime.Now;
                    }
                }

                if (dr.Length > 0)
                {
                    foreach (var row in dr)
                    {
                        row["other_score"] = intScore;
                        row["other_comment"] = strComment;
                        row["updated_by"] = ssMng.EmpSeq;
                        row["updated_when"] = DateTime.Now;
                    }
                }
                else
                {
                    DataRow drow = dtOther.NewRow();
                    drow["evaluation_detail_seq"] = intId;
                    drow["other_seq"] = ssMng.EmpSeq;
                    drow["other_score"] = intScore;
                    drow["other_comment"] = strComment;
                    drow["created_by"] = ssMng.EmpSeq;
                    drow["created_when"] = DateTime.Now;
                    drow["record_status"] = "U";
                    dtOther.Rows.Add(drow);
                }
            }

            DataSet ds = new DataSet();
            ds.Tables.Add(dtHeader.Copy());
            ds.Tables.Add(dtOther.Copy());

            return ds;
        }

        protected DataSet ScoreCoreCompetency(DataTable dtHeader, DataTable dtOther)
        {
            int intEmpSeq = Convert.ToInt32(Request.QueryString["ESeq"]);
            DataTable dtGetExpectResult = cmd.GetExpectResult(intEmpSeq);

            Double dblTotalMaxValue = 0.0;
            Double dblSupGrandTotalIsWeight = 0.0;
            Double dblSupGrandTotalWeight = 0.0;
            Double dblSupTotalScore = 0.0;
            Double dblSupTotal = 0.0;
            bool isWeight = false;

            foreach (GridDataItem item in grdRadCoreCompetency.MasterTableView.Items)
            {
                RadioButtonList rblSupScore = (RadioButtonList)item.FindControl("rblSupervisorScore");
                RadTextBox txtSupComment = (RadTextBox)item.FindControl("txtSupervisorComment");
                RadioButtonList rblEmpScore = (RadioButtonList)item.FindControl("rblEmployeeScore");
                RadTextBox txtEmpComment = (RadTextBox)item.FindControl("txtEmployeeComment");
                HiddenField hdfExpectScore = (HiddenField)item.FindControl("hdfCC");

                rblEmpScore.Enabled = false;
                txtEmpComment.Enabled = false;

                int intScore = 0;
                int intFullScore = main.ConvertDefaultInt(item["full_score"].Text);
                int intWeight = main.ConvertDefaultInt(item["weight"].Text);
                int intId = main.ConvertDefaultInt(item.GetDataKeyValue("evaluation_detail_seq").ToString());
                int intEvaluationListSeq = main.ConvertDefaultInt(item["evaluation_list_seq"].Text);
                int intEntityID = main.ConvertDefaultInt(item["detail_entity_seq"].Text);

                isWeight = Convert.ToBoolean(main.ConvertDefaultInt(item["isdetailweight"].Text));

                DataRow[] dr = dtOther.Select(string.Format("evaluation_detail_seq = {0}", intId), "");
                DataRow[] drHeader = dtHeader.Select(string.Format("evaluation_list_seq = {0}", intEvaluationListSeq), "");
                DataRow[] drExpect = dtGetExpectResult.Select(string.Format("pos_competency_seq = {0}", intEntityID), "");
                if (drExpect.Length > 0)
                {
                    foreach (var row in drExpect)
                    {
                        hdfExpectScore.Value = row["expect_result"].ToString();
                    }
                }

                if (rblSupScore != null)
                {
                    intScore = Convert.ToInt32(rblSupScore.SelectedValue);
                }

                string strComment = "";
                if (txtSupComment != null)
                {
                    strComment = txtSupComment.Text;
                }

                int intSupInScore = 0;
                int intExpectScore = main.ConvertDefaultInt(hdfExpectScore.Value);


                if (intExpectScore == 5)
                {
                    intSupInScore = (intScore - intExpectScore) + 5;
                }
                else
                {
                    intSupInScore = (intScore - intExpectScore) + 4;

                    if (intSupInScore > 5)
                    {
                        intSupInScore = 5;
                    }
                }

                if (isWeight)
                {
                    dblSupTotal = (intSupInScore * intWeight) / intFullScore;
                    dblSupTotalScore += intFullScore;
                }
                else
                {
                    dblTotalMaxValue += intFullScore;
                }
                dblSupGrandTotalIsWeight += dblSupTotal;
                dblSupGrandTotalWeight = (dblSupTotalScore / dblTotalMaxValue) * 100.0;


                ////////////////////////////////////////////////////////////////////////////                
                if (drHeader.Length > 0)
                {
                    foreach (var rowHD in drHeader)
                    {
                        rowHD["remark"] = txtRadRemarkCoreCompetency.Text;

                        if (isWeight)
                        { rowHD["supervisor_total_score"] = dblSupGrandTotalIsWeight; }
                        else
                        { rowHD["supervisor_total_score"] = dblSupGrandTotalWeight; }

                        rowHD["updated_by"] = ssMng.EmpSeq;
                        rowHD["updated_when"] = DateTime.Now;
                    }
                }

                if (dr.Length > 0)
                {
                    foreach (var row in dr)
                    {
                        row["other_score"] = intScore;
                        row["other_comment"] = strComment;
                        row["updated_by"] = ssMng.EmpSeq;
                        row["updated_when"] = DateTime.Now;
                    }
                }
                else
                {
                    DataRow drow = dtOther.NewRow();
                    drow["evaluation_detail_seq"] = intId;
                    drow["other_seq"] = ssMng.EmpSeq;
                    drow["other_score"] = intScore;
                    drow["other_comment"] = strComment;
                    drow["created_by"] = ssMng.EmpSeq;
                    drow["created_when"] = DateTime.Now;
                    drow["record_status"] = "U";
                    dtOther.Rows.Add(drow);
                }
            }

            GridFooterItem footerItem = (GridFooterItem)grdRadCoreCompetency.MasterTableView.GetItems(GridItemType.Footer)[0];
            Label lblSupGrandCoreCompetencyTotal = (Label)footerItem.FindControl("lblFooterCoreCompetencySupTotalScore");

            if (isWeight)
            {
                lblSupGrandCoreCompetencyTotal.Text = String.Format("{0:N0}", dblSupGrandTotalIsWeight) + " %";
            }
            else
            {
                lblSupGrandCoreCompetencyTotal.Text = String.Format("{0:N0}", dblSupGrandTotalWeight) + " %";
            }

            DataSet ds = new DataSet();
            ds.Tables.Add(dtHeader.Copy());
            ds.Tables.Add(dtOther.Copy());

            return ds;

        }

        protected DataSet ScoreIDP(DataTable dtHeader, DataTable dtOther)
        {
            foreach (GridDataItem item in grdRadIDP.MasterTableView.Items)
            {
                int intId = main.ConvertDefaultInt(item.GetDataKeyValue("evaluation_detail_seq"));
                int intEvaluationListSeq = main.ConvertDefaultInt(item["evaluation_list_seq"].Text);

                DataRow[] dr = dtOther.Select(string.Format("evaluation_detail_seq = {0}", intId), "");
                DataRow[] drHeader = dtHeader.Select(string.Format("evaluation_list_seq = {0}", intEvaluationListSeq), "");

                RadioButtonList rblScore = (RadioButtonList)item.FindControl("rblSupervisorScore");
                int intScore = 0;
                if (rblScore != null)
                {
                    intScore = main.ConvertDefaultInt(rblScore.SelectedValue);
                }

                RadTextBox txtComment = (RadTextBox)item.FindControl("txtSupervisorComment");
                string strComment = "";
                if (txtComment != null)
                {
                    strComment = txtComment.Text;
                }

                if (drHeader.Length > 0)
                {
                    foreach (var rowHD in drHeader)
                    {
                        rowHD["remark"] = txtRadRemarkIDP.Text;
                        rowHD["supervisor_total_score"] = DBNull.Value;
                        rowHD["supervisor_total_score"] = DBNull.Value;
                        rowHD["updated_by"] = ssMng.EmpSeq;
                        rowHD["updated_when"] = DateTime.Now;
                    }
                }

                if (dr.Length > 0)
                {
                    foreach (var row in dr)
                    {
                        row["other_score"] = intScore;
                        row["other_comment"] = strComment;
                        row["updated_by"] = ssMng.EmpSeq;
                        row["updated_when"] = DateTime.Now;
                    }
                }
                else
                {
                    DataRow drow = dtOther.NewRow();
                    drow["evaluation_detail_seq"] = intId;
                    drow["other_seq"] = ssMng.EmpSeq;
                    drow["other_score"] = intScore;
                    drow["other_comment"] = strComment;
                    drow["created_by"] = ssMng.EmpSeq;
                    drow["created_when"] = DateTime.Now;
                    drow["record_status"] = "U";
                    dtOther.Rows.Add(drow);
                }
            }

            DataSet ds = new DataSet();
            ds.Tables.Add(dtHeader.Copy());
            ds.Tables.Add(dtOther.Copy());

            return ds;
        }

        protected void DisibleRadioButtonListKPA(DataRow[] dr)
        {
            grdRadKPA.DataSource = dr;
            grdRadKPA.DataBind();
            
            List<DataRow> list = dr.AsEnumerable().ToList();

            foreach (GridDataItem item in grdRadKPA.MasterTableView.Items)
            {
                int intId = Convert.ToInt32(item.GetDataKeyValue("detail_entity_seq"));

                RadioButtonList rblSupScore = (RadioButtonList)item.FindControl("rblSupervisorScore");
                RadTextBox txtSupComment = (RadTextBox)item.FindControl("txtSupervisorComment");
                RadioButtonList rblEmpScore = (RadioButtonList)item.FindControl("rblEmployeeScore");
                RadTextBox txtEmpComment = (RadTextBox)item.FindControl("txtEmployeeComment");

                rblEmpScore.Enabled = false;
                txtEmpComment.Enabled = false;

                item["key_area_name"].Text = list[item.ItemIndex]["detail_description"].ToString();
                item["description"].Text = list[item.ItemIndex]["long_description"].ToString();
                
                txtEmpComment.Text = list[item.ItemIndex]["employee_comment"].ToString();
                rblEmpScore.SelectedValue = list[item.ItemIndex]["employee_score"].ToString();
                txtSupComment.Text = list[item.ItemIndex]["other_comment"].ToString();
                rblSupScore.SelectedValue = list[item.ItemIndex]["other_score"].ToString();
                txtRadRemarkKPA.Text = list[item.ItemIndex]["remark"].ToString();

                GridFooterItem footerItem = (GridFooterItem)grdRadKPA.MasterTableView.GetItems(GridItemType.Footer)[0];
                Label lblEmpGrandTotal = (Label)footerItem.FindControl("lblFooterTotalScore");
                Label lblSupGrandTotal = (Label)footerItem.FindControl("lblFooterKPASupTotalScore");
                lblSupGrandTotal.Text = list[item.ItemIndex]["supervisor_total_score"].ToString();
                lblEmpGrandTotal.Text = list[item.ItemIndex]["employee_total_score"].ToString();               
            }
        }

        protected void DisibleRadioButtonListStrategy(DataRow[] dr)
        {
            grdRadStrategyProject.DataSource = dr;
            grdRadStrategyProject.DataBind();
            
            List<DataRow> list = dr.AsEnumerable().ToList();

            foreach (GridDataItem item in grdRadStrategyProject.MasterTableView.Items)
            {
                RadioButtonList rblSupScore = (RadioButtonList)item.FindControl("rblSupervisorScore");
                RadTextBox txtSupComment = (RadTextBox)item.FindControl("txtSupervisorComment");
                RadioButtonList rblEmpScore = (RadioButtonList)item.FindControl("rblEmployeeScore");
                RadTextBox txtEmpComment = (RadTextBox)item.FindControl("txtEmployeeComment");

                rblEmpScore.Enabled = false;
                txtEmpComment.Enabled = false;

                item["bgm_proj_name"].Text = list[item.ItemIndex]["detail_description"].ToString();
                item["job_title"].Text = list[item.ItemIndex]["long_description"].ToString();

                txtEmpComment.Text = list[item.ItemIndex]["employee_comment"].ToString();                    
                rblEmpScore.SelectedValue = list[item.ItemIndex]["employee_score"].ToString();

                if (list[item.ItemIndex]["other_comment"] != DBNull.Value)
                {
                    txtSupComment.Text = list[item.ItemIndex]["other_comment"].ToString();
                }

                if (list[item.ItemIndex]["other_score"] != DBNull.Value)
                {
                    rblSupScore.SelectedValue = list[item.ItemIndex]["other_score"].ToString();
                }

                txtRadRemarkStrategy.Text = list[item.ItemIndex]["remark"].ToString();

                GridFooterItem footerItem = (GridFooterItem)grdRadStrategyProject.MasterTableView.GetItems(GridItemType.Footer)[0];
                Label lblEmpGrandStrategyTotal = (Label)footerItem.FindControl("lblFooterStrategyTotalScore");
                Label lblSupGrandStrategyTotal = (Label)footerItem.FindControl("lblFooterStrategySupTotalScore");

                lblSupGrandStrategyTotal.Text = list[item.ItemIndex]["supervisor_total_score"].ToString();
                lblEmpGrandStrategyTotal.Text = list[item.ItemIndex]["employee_total_score"].ToString();
            }

        }

        protected void DisibleRadioButtonListCoreCompetency(DataRow[] dr)
        {
            grdRadCoreCompetency.DataSource = dr;
            grdRadCoreCompetency.DataBind();

            List<DataRow> list = dr.AsEnumerable().ToList();
            
            foreach (GridDataItem item in grdRadCoreCompetency.MasterTableView.Items)
            {
                RadioButtonList rblSupScore = (RadioButtonList)item.FindControl("rblSupervisorScore");
                RadTextBox txtSupComment = (RadTextBox)item.FindControl("txtSupervisorComment");
                RadioButtonList rblEmpScore = (RadioButtonList)item.FindControl("rblEmployeeScore");
                RadTextBox txtEmpComment = (RadTextBox)item.FindControl("txtEmployeeComment");
                
                rblEmpScore.Enabled = false;
                txtEmpComment.Enabled = false;

                item["core_competency_name"].Text = list[item.ItemIndex]["detail_description"].ToString();
                item["level_name"].Text = list[item.ItemIndex]["long_description"].ToString();

                txtSupComment.Text = list[item.ItemIndex]["other_comment"].ToString();
                rblSupScore.SelectedValue = list[item.ItemIndex]["other_score"].ToString();
                txtEmpComment.Text = list[item.ItemIndex]["employee_comment"].ToString();
                rblEmpScore.SelectedValue = list[item.ItemIndex]["employee_score"].ToString();
                txtRadRemarkCoreCompetency.Text = list[item.ItemIndex]["remark"].ToString();

                GridFooterItem footerItem = (GridFooterItem)grdRadCoreCompetency.MasterTableView.GetItems(GridItemType.Footer)[0];
                Label lblSupGrandCoreCompetencyTotal = (Label)footerItem.FindControl("lblFooterCoreCompetencySupTotalScore");
                Label lblEmpGrandCoreCompetencyTotal = (Label)footerItem.FindControl("lblFooterCoreCompetencyTotalScore");
                lblSupGrandCoreCompetencyTotal.Text = list[item.ItemIndex]["supervisor_total_score"].ToString();
                lblEmpGrandCoreCompetencyTotal.Text = list[item.ItemIndex]["employee_total_score"].ToString();
            }

            
        }

        protected void DisibleRadioButtonListIDP(DataRow[] dr)
        {
            grdRadIDP.DataSource = dr;
            grdRadIDP.DataBind();

            List<DataRow> list = dr.AsEnumerable().ToList();

            foreach (GridDataItem item in grdRadIDP.MasterTableView.Items)
            {
                RadioButtonList rblSupScore = (RadioButtonList)item.FindControl("rblSupervisorScore");
                RadTextBox txtSupComment = (RadTextBox)item.FindControl("txtSupervisorComment");
                RadioButtonList rblEmpScore = (RadioButtonList)item.FindControl("rblEmployeeScore");
                RadTextBox txtEmpComment = (RadTextBox)item.FindControl("txtEmployeeComment");

                rblEmpScore.Enabled = false;
                txtEmpComment.Enabled = false;

                item["type_name"].Text = list[item.ItemIndex]["detail_description"].ToString();
                item["proficiency_name"].Text = list[item.ItemIndex]["long_description"].ToString();

                txtSupComment.Text = list[item.ItemIndex]["other_comment"].ToString();
                rblSupScore.SelectedValue = list[item.ItemIndex]["other_score"].ToString();
                txtEmpComment.Text = list[item.ItemIndex]["employee_comment"].ToString();
                rblEmpScore.SelectedValue = list[item.ItemIndex]["employee_score"].ToString();
                txtRadRemarkIDP.Text = list[item.ItemIndex]["remark"].ToString();
            }

        }

        protected void InsertAndEditResultIdpDevPlan()
        {
            int intEmpSeq = Convert.ToInt32(Request.QueryString["ESeq"]);
            int intRoundSeq = Convert.ToInt32(Request.QueryString["RSeq"]);

            //MySqlConnection conn = new MySqlConnection(SystemInfo._ConnectionString);
            SqlConnection conn = new SqlConnection(SystemInfo._ConnectionString);

            try
            {
                StringBuilder sb = new StringBuilder();
                //sb.AppendLine("SELECT o.* FROM hrd_evaluation_header h");
                //sb.AppendLine("INNER JOIN hrd_evaluation_detail d ON h.evaluation_seq = d.evaluation_seq");
                //sb.AppendLine("INNER JOIN hrd_evaluation_individual_dev_plan o ON o.evaluation_detail_seq = d.evaluation_detail_seq");
                //sb.AppendFormat("WHERE h.emp_seq = {0} ", intEmpSeq);
                //sb.AppendFormat("AND h.evaluation_round_seq = {0}", intRoundSeq);

                sb.AppendLine("SELECT * FROM hrd_evaluation_individual_dev_plan");

                //MySqlDataAdapter daResult = new MySqlDataAdapter(sb.ToString(), conn);
                //MySqlCommandBuilder comdBuilderOther = new MySqlCommandBuilder(daResult);
                //DataTable dtResult = new DataTable();
                //daResult.Fill(dtResult);

                SqlDataAdapter daResult = new SqlDataAdapter(sb.ToString(), conn);
                SqlCommandBuilder comdBuilderOther = new SqlCommandBuilder(daResult);
                DataTable dtResult = new DataTable();
                daResult.Fill(dtResult);

                foreach (GridDataItem item in grdRadResultIDP.MasterTableView.Items)
                {
                    int intId = Convert.ToInt32(item.GetDataKeyValue("evaluation_detail_seq"));
                    DataRow[] dr = dtResult.Select(string.Format("evaluation_detail_seq = {0}", intId), "");

                    RadComboBox cboDevMethod = (RadComboBox)item.FindControl("cboRadDevMethod");
                    RadioButtonList rblPriority = (RadioButtonList)item.FindControl("rblPriority");
                    RadioButtonList rblQuarter = (RadioButtonList)item.FindControl("rblQuarter");
                    RadTextBox txtReason = (RadTextBox)item.FindControl("txtReason");

                    int intGapResult = Convert.ToInt32(item["gap_result"].Text);
                    int? intDevMethod;
                    int? intPriority;
                    int? intPeriod;

                   
                     if (cboDevMethod.SelectedIndex > 0)
                    {
                        intDevMethod = Convert.ToInt32(cboDevMethod.SelectedValue);
                    }
                    else
                    {
                        intDevMethod = null;
                    }

                    if (rblPriority.SelectedIndex > -1)
                    {
                        intPriority = Convert.ToInt32(rblPriority.SelectedValue);
                    }
                    else
                    {
                        intPriority = null;
                    }

                    if (rblQuarter.SelectedIndex > -1)
                    {
                        intPeriod = Convert.ToInt32(rblQuarter.SelectedValue);
                    }
                    else
                    {
                        intPeriod = null;
                    }


                    if (dr.Length > 0)
                    {
                        foreach (var row in dr)
                        {


                            if (intDevMethod == null)
                                row["dev_method_seq"] = DBNull.Value;
                            else
                                row["dev_method_seq"] = intDevMethod;

                            row["gap_result"] = intGapResult;

                            if (intPriority == null)
                                row["priority"] = DBNull.Value;
                            else
                                row["priority"] = intPriority;

                            if (intPeriod == null)
                                row["period"] = DBNull.Value;
                            else
                                row["period"] = intPeriod;

                            row["remark"] = txtReason.Text;
                            row["updated_by"] = ssMng.EmpSeq;
                            row["updated_when"] = DateTime.Now;
                        }
                    }
                    else
                    {

                        DataRow drow = dtResult.NewRow();

                        drow["evaluation_detail_seq"] = intId;

                        if (intDevMethod == null)
                            drow["dev_method_seq"] = DBNull.Value ;
                        else
                            drow["dev_method_seq"] = intDevMethod;

                        drow["gap_result"] = intGapResult;

                        if (intPriority == null)
                            drow["priority"] = DBNull.Value;    
                        else
                            drow["priority"] = intPriority;

                        if (intPeriod == null)
                            drow["period"] = DBNull.Value;
                        else
                            drow["period"] = intPeriod;

                        drow["remark"] = txtReason.Text;
                        drow["created_by"] = ssMng.EmpSeq;
                        drow["created_when"] = DateTime.Now;
                        drow["record_status"] = "U";
                        dtResult.Rows.Add(drow);
                    }
                }

                daResult.Update(dtResult.Select(null, null, DataViewRowState.Deleted));

                daResult.Update(dtResult.Select(null, null, DataViewRowState.ModifiedCurrent));

                daResult.Update(dtResult.Select(null, null, DataViewRowState.Added));
               
                var strParamUser = Request.QueryString["YSeq"];
                var strParamRound = Request.QueryString["RSeq"];
                var strParamEmp = Request.QueryString["ESeq"];
                Response.Redirect(string.Format("HRDEvaluationSupervisor.aspx?YSeq={0}&RSeq={1}&ESeq={2}&Re={3}", strParamUser, strParamRound, strParamEmp, 1));

                }
                catch (Exception ex)
                {
                    Session["error"] = Convert.ToString(Session["error"]) + ex.Message;
                }
                finally
                {
                    conn.Close();
                }

            
        }

        protected void LoadResultIdp(DataTable dt)
        {
            grdRadResultIDP.DataSource = dt;
            grdRadResultIDP.DataBind();

            List<DataRow> list = dt.AsEnumerable().ToList();

            foreach (GridDataItem item in grdRadResultIDP.MasterTableView.Items)
            {
                RadComboBox cboDevMethod = (RadComboBox)item.FindControl("cboRadDevMethod");
                RadioButtonList rblPriority = (RadioButtonList)item.FindControl("rblPriority");
                RadioButtonList rblQuarter = (RadioButtonList)item.FindControl("rblQuarter");
                RadTextBox txtReason = (RadTextBox)item.FindControl("txtReason");

                int intDetailSeq = Convert.ToInt32(item.GetDataKeyValue("evaluation_detail_seq"));

                cboDevMethod.SelectedValue = list[item.ItemIndex]["dev_method_seq"].ToString();
                rblPriority.SelectedValue = list[item.ItemIndex]["priority"].ToString(); 
                rblQuarter.SelectedValue = list[item.ItemIndex]["period"].ToString(); 
                txtReason.Text = list[item.ItemIndex]["remark"].ToString(); 
            }
        }

       
    }
}